﻿using Memo.Electricity.Game;
using System.Collections.Generic;
using UnityEngine;

namespace Memo.Electricity.Engine
{
    public class LightningComb : MemoBehaviour
    {
        public GameObject line;
        public int lineCount = 3;
        public Color lineColor;

        [SerializeField]
        private List<Transform> transforms;

		#region 当前显示的闪电的缓存

		private struct LightningInfo
		{
            public Transform start;
            public Transform end;
		}
        private Dictionary<LightningInfo, GameObject> mLightningCache;

		#endregion


		private void Awake()
		{
			mLightningCache = new Dictionary<LightningInfo, GameObject>();
		}

		// Update is called once per frame
        private void Update()
        {
	        transforms = CRelay.ConnectPath;
	        Dictionary<LightningInfo, GameObject> newCache = new Dictionary<LightningInfo, GameObject>();
	        if (transforms != null)
	        {
				for (int i = 0; i < transforms.Count - 1; i++)
				{
					LightningInfo info = new LightningInfo();
					info.start = transforms[i];
					info.end = transforms[i + 1];
					if (!mLightningCache.ContainsKey(info))
					{
						var go = GenLightningLines(line, lineCount, transforms[i], transforms[i + 1]);
						if (go != null)
							newCache.Add(info, go);
					}
					else
					{
						newCache.Add(info, mLightningCache[info]);
					}
				}
			}
	        foreach (var key in mLightningCache.Keys)
            {
	            if (!newCache.ContainsKey(key))
		            Destroy(mLightningCache[key]);
            }
            mLightningCache = newCache;

        }

        private GameObject GenLightningLines(GameObject line, int count, Transform startPos, Transform endPos)
        {
	        GameObject lightningGo = new GameObject("Lightning");
	        lightningGo.transform.parent = transform;
            for (int i = 0; i < count; i++)
            {
                GameObject InsLine = Instantiate(line);
                InitlightningLine(InsLine);
                InsLine.transform.parent = lightningGo.transform;
                LightningController lightning = InsLine.GetComponent<LightningController>();
                if (lightning == null)
                {
                    Debug.LogError("GameObject line doesn't have a 'LightningController' component!");
                    Destroy(lightningGo);
                    Destroy(InsLine);
                    return null;
                }
                lightning.m_Star = startPos;
                lightning.m_End = endPos;
                lightning.Init();
            }

            return lightningGo;
        }

        private void InitlightningLine(GameObject line)
        {
            //line.GetComponent<Material>().color = lineColor;
            
        }
    }
}